// 权限管理前端交互脚本
// 基于静态配置的权限管理，支持启用/禁用权限

document.addEventListener('DOMContentLoaded', function () {
    const permissionModules = document.querySelector('.permission-modules');
    const modal = document.getElementById('permissionDetailModal');
    const closeBtn = document.querySelector('.close');
    
    let currentPermission = null;

    // 关闭模态框
    closeBtn.addEventListener('click', function() {
        closeModal();
    });
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            closeModal();
        }
    });

    // 加载权限配置和状态
    function loadPermissions() {
        // 首先获取静态配置中的权限定义
        fetch('/api/config/all_field_config', {
            headers: {
                'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
            }
        })
        .then(response => response.json())
        .then(configData => {
            if (configData.success) {
                const permissionConfig = configData.data.PERMISSION_FEATURE_MAP;
                // 然后获取数据库中已存在的权限状态
                return fetch('/api/admin/permissions', {
                    headers: {
                        'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
                    }
                })
                .then(response => response.json())
                .then(permissionData => {
                    if (permissionData.success) {
                        renderPermissions(permissionConfig, permissionData.data);
                    } else {
                        renderPermissions(permissionConfig, []);
                    }
                });
            }
        })
        .catch(error => {
            console.error('加载权限配置失败:', error);
            permissionModules.innerHTML = '<div class="alert alert-danger">加载权限配置失败</div>';
        });
    }

    // 渲染权限列表
    function renderPermissions(permissionConfig, existingPermissions) {
        permissionModules.innerHTML = '';
        
        // 将现有权限转换为Map，便于查找
        const permissionMap = new Map();
        existingPermissions.forEach(p => {
            permissionMap.set(p.code, p);
        });

        // 遍历静态配置中的权限
        Object.keys(permissionConfig).forEach(moduleKey => {
            const module = permissionConfig[moduleKey];
            const moduleDiv = document.createElement('div');
            moduleDiv.className = 'permission-module';
            
            // 模块标题
            const moduleHeader = document.createElement('div');
            moduleHeader.className = 'module-header';
            moduleHeader.textContent = module.display_name;
            moduleDiv.appendChild(moduleHeader);
            
            // 模块内容
            const moduleContent = document.createElement('div');
            moduleContent.className = 'module-content';
            
            // 遍历模块中的权限
            Object.keys(module.features).forEach(featureKey => {
                const feature = module.features[featureKey];
                const permissionCode = feature.permission_code;
                const existingPermission = permissionMap.get(permissionCode);
                
                const permissionItem = document.createElement('div');
                permissionItem.className = 'permission-item';
                
                // 权限信息
                const permissionInfo = document.createElement('div');
                permissionInfo.className = 'permission-info';
                permissionInfo.innerHTML = `
                    <div class="permission-code">${permissionCode}</div>
                    <div class="permission-name">${feature.display_name}</div>
                    <div class="permission-description">${feature.description}</div>
                `;
                
                // 权限操作
                const permissionActions = document.createElement('div');
                permissionActions.className = 'permission-actions';
                
                const status = existingPermission ? (existingPermission.status || 'enabled') : 'disabled';
                const statusBadge = document.createElement('span');
                statusBadge.className = `status-badge status-${status}`;
                statusBadge.textContent = status === 'enabled' ? '已启用' : '未启用';
                
                const editBtn = document.createElement('button');
                editBtn.className = 'btn btn-sm btn-outline-primary btn-edit';
                editBtn.textContent = '编辑';
                editBtn.onclick = () => openPermissionModal(permissionCode, feature, existingPermission);
                
                // 添加日志按钮
                const logBtn = document.createElement('button');
                logBtn.className = 'btn btn-sm btn-outline-info btn-log';
                logBtn.textContent = '日志';
                logBtn.onclick = () => viewPermissionLog(permissionCode, existingPermission);
                
                permissionActions.appendChild(statusBadge);
                permissionActions.appendChild(editBtn);
                permissionActions.appendChild(logBtn);
                
                permissionItem.appendChild(permissionInfo);
                permissionItem.appendChild(permissionActions);
                moduleContent.appendChild(permissionItem);
            });
            
            moduleDiv.appendChild(moduleContent);
            permissionModules.appendChild(moduleDiv);
        });
    }

    // 打开权限编辑模态框
    function openPermissionModal(permissionCode, feature, existingPermission) {
        console.log('打开权限模态框:', { permissionCode, feature, existingPermission });
        
        currentPermission = {
            code: permissionCode,
            feature: feature,
            existing: existingPermission
        };
        
        // 填充模态框内容
        document.getElementById('permissionCode').value = permissionCode;
        document.getElementById('permissionName').value = feature.display_name;
        document.getElementById('permissionDescription').value = feature.description;
        
        const status = existingPermission ? (existingPermission.status || 'enabled') : 'disabled';
        document.getElementById('permissionStatus').value = status;
        
        document.getElementById('modalTitle').textContent = `编辑权限: ${feature.display_name}`;
        modal.style.display = 'block';
    }

    // 关闭模态框
    window.closeModal = function() {
        modal.style.display = 'none';
        currentPermission = null;
    };

    // 保存权限
    window.savePermission = function() {
        if (!currentPermission) return;
        
        console.log('当前权限对象:', currentPermission);
        console.log('权限代码:', currentPermission.code);
        
        const status = document.getElementById('permissionStatus').value;
        const permissionData = {
            code: currentPermission.code,
            name: currentPermission.feature.display_name,
            description: currentPermission.feature.description,
            status: status
        };
        
        console.log('权限数据:', permissionData);
        
        // 统一使用PUT请求，如果权限不存在，使用权限代码作为参数
        const method = 'PUT';
        console.log('existing对象:', currentPermission.existing);
        console.log('existing.id:', currentPermission.existing?.id);
        
        const url = currentPermission.existing && currentPermission.existing.id && currentPermission.existing.id !== null
            ? `/api/admin/permissions/${currentPermission.existing.id}`
            : `/api/admin/permissions/${currentPermission.code}`;
        
        console.log('请求URL:', url);
        
        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
            },
            body: JSON.stringify(permissionData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                closeModal();
                loadPermissions(); // 重新加载权限列表
                alert('权限保存成功');
            } else {
                alert(data.message || '保存失败');
            }
        })
        .catch(error => {
            console.error('保存权限失败:', error);
            alert('保存失败');
        });
    };

    // 初始加载
    loadPermissions();
});

// 查看权限日志
window.viewPermissionLog = function(permissionCode, existingPermission) {
    const token = localStorage.getItem('access_token') || '';
    if (!token) {
        if (window.Swal) {
            Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
        } else {
            alert('未检测到登录凭证，请重新登录后再试。');
        }
        return;
    }
    
    // 使用权限代码或ID查询日志
    const targetId = existingPermission && existingPermission.id ? existingPermission.id : permissionCode;
    
    // 使用统一日志系统查询权限操作日志
    fetch(`/api/admin/logs?target_id=${targetId}&action=UPDATE,CREATE,DELETE`, {
            headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
        }
    })
    .then((response) => {
        if (response.status === 401) throw new Error('未认证或Token无效');
        return response.json();
    })
    .then((data) => {
        if (data.success && data.data && data.data.length > 0) {
            // Format logs for display
            let html = data.data
                .map((log) => {
                    let localTime = log.operation_time
                        ? new Date(log.operation_time).toLocaleString()
                        : "";
                    let restoreButton = "";

                    // 根据日志类型显示不同的恢复按钮
                    const actionLower = log.action.toLowerCase();
                    if (actionLower === "delete") {
                        restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restorePermissionLog(${log.id})">恢复已删除权限</button>`;
                    } else if (actionLower === "restore") {
                        restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
                    } else if (
                        log.old_content &&
                        (actionLower === "create" || actionLower === "update")
                    ) {
                        restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restorePermissionLog(${log.id})">恢复此版本</button>`;
                    }

                    return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
                        <div><strong>操作类型：</strong>${log.action} | <strong>操作人：</strong>${log.operator || '系统'} | <strong>时间：</strong>${localTime}</div>
                        ${log.new_content ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>` : ""}
                        ${log.old_content ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${log.old_content}</pre>${restoreButton ? `<div style="margin-top:8px;">${restoreButton}</div>` : ""}</div>` : ""}
                    </div>`;
                })
                .join("");

            if (window.Swal) {
                Swal.fire({
                    title: '权限操作日志',
                    html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
                    width: 1000,
                    showConfirmButton: false,
                    showCloseButton: true,
                });
            } else {
                alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
            }
        } else {
            if (window.Swal) {
                Swal.fire("无日志", "该权限暂无操作日志", "info");
            } else {
                alert("该权限暂无操作日志");
            }
        }
    })
    .catch((error) => {
        if (window.Swal) {
            Swal.fire("获取日志失败", "网络错误：" + error.message, "error");
        } else {
            alert("获取权限日志失败: " + error.message);
        }
    });
};

// 恢复权限日志
window.restorePermissionLog = function(logId) {
    const token = localStorage.getItem('access_token') || '';
    if (!token) {
        if (window.Swal) {
            Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
        } else {
            alert('未检测到登录凭证，请重新登录后再试。');
        }
        return;
    }
    
    if (window.Swal) {
        Swal.fire({
            title: '确认恢复',
            text: '确定要恢复此版本的权限信息吗？',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '确定恢复',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                performPermissionRestore(logId, token);
            }
        });
    } else {
        if (confirm('确定要恢复此版本的权限信息吗？')) {
            performPermissionRestore(logId, token);
        }
    }
};

// 执行权限恢复操作
function performPermissionRestore(logId, token) {
    fetch(`/api/admin/logs/${logId}/restore`, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (window.Swal) {
                Swal.fire('恢复成功', '权限信息已恢复到指定版本', 'success');
            } else {
                alert('恢复成功');
            }
            // 重新加载权限列表
    loadPermissions();
        } else {
            if (window.Swal) {
                Swal.fire('恢复失败', data.message || '恢复操作失败', 'error');
            } else {
                alert('恢复失败: ' + (data.message || '恢复操作失败'));
            }
        }
    })
    .catch(error => {
        if (window.Swal) {
            Swal.fire('恢复失败', '网络错误：' + error.message, 'error');
        } else {
            alert('恢复失败: ' + error.message);
        }
    });
}
